package com.ruoyi.system.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.controller.es.EsUnService;
import com.ruoyi.system.controller.es.dto.EsSearch;
import com.ruoyi.system.domain.FyData;
import com.ruoyi.system.domain.FyProject;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.service.IFyDataService;
import com.ruoyi.system.service.IFyProjectService;
import com.ruoyi.system.util.UniqueIdGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.FyPeople;
import com.ruoyi.system.service.IFyPeopleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 传承人信息Controller
 *
 * @author ruoyi
 * @date 2025-06-05
 */
@RestController
@RequestMapping("/system/people")
public class FyPeopleController extends BaseController
{
    @Autowired
    private IFyPeopleService fyPeopleService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    RuoYiConfig ruoYiConfig;
    @Autowired
    private IFyDataService fyDataService;
    @Autowired
    private IFyProjectService fyProjectService;
    @Autowired
    private EsUnService esUnService;
    /**
     * 查询传承人信息列表
     */
//    @PreAuthorize("@ss.hasPermi('system:people:list')")
    @GetMapping("/list")
    public TableDataInfo list(FyPeople fyPeople)
    {
        startPage();
        List<FyPeople> list = fyPeopleService.selectFyPeopleList(fyPeople);
        return getDataTable(list);
    }

//    @GetMapping("/tongbu")
//    public AjaxResult list22()
//    {
//        List<FyPeople> list = fyPeopleService.selectFyPeopleList(null);
//        for (FyPeople fp:list){
//            FyData fyData=new FyData();
//            fyData.setProjectId(fp.getProjectId());
//            List<FyData> datas=fyDataService.selectFyDataList(fyData);
//            for (FyData da:datas){
//                fyData.setPeopleId(da.getPeopleId());
//                fyData.setPeopleName(da.getPeopleName());
//                fyDataService.updateFyData(fyData);
//            }
//
//        }
//        return AjaxResult.success();
//    }


    /**
     * 导出传承人信息列表
     */
//    @PreAuthorize("@ss.hasPermi('system:people:export')")
    @Log(title = "传承人信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FyPeople fyPeople)
    {
        List<FyPeople> list = fyPeopleService.selectFyPeopleList(fyPeople);
        ExcelUtil<FyPeople> util = new ExcelUtil<FyPeople>(FyPeople.class);
        util.exportExcel(response, list, "传承人信息数据");
    }

    /**
     * 获取传承人信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:people:query')")
    @GetMapping( "/getInfo")
    public AjaxResult getInfo(Long peopleId)
    {
        return success(fyPeopleService.selectFyPeopleByPeopleId(peopleId));
    }

    /**
     * 新增传承人信息
     */
//    @PreAuthorize("@ss.hasPermi('system:people:add')")
    @Log(title = "传承人信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody FyPeople fyPeople)
    {
//        redisCache.deleteObject("home:count");
        fyPeople.setPeopleId(Long.valueOf(DateUtils.dateTimeNow()));
        EsSearch esSearch=new EsSearch();
        esSearch.setId(fyPeople.getPeopleId());
        esSearch.setLanmu("资源-非遗传承人");
        esSearch.setLanmuId(2);
        esSearch.setTitle(fyPeople.getPeopleName());
        esSearch.setContent(fyPeople.getPeopleBrief());
        esUnService.save(esSearch);
        if (com.ruoyi.common.utils.StringUtils.isNotEmpty(fyPeople.getProjectName())){
            FyProject fyProject=new FyProject();
            fyPeople.setProjectName(fyPeople.getProjectName());
          List<FyProject> projectList=  fyProjectService.selectFyProjectList(fyProject);
          if (com.ruoyi.common.utils.StringUtils.isNotEmpty(projectList)){
              fyPeople.setProjectType(projectList.get(0).getProjectType());
              fyPeople.setProjectBatch(projectList.get(0).getProjectBatch());
          }
        }

        return toAjax(fyPeopleService.insertFyPeople(fyPeople));
    }

    /**
     * 修改传承人信息
     */
//    @PreAuthorize("@ss.hasPermi('system:people:edit')")
    @Log(title = "传承人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody FyPeople fyPeople)
    {

        EsSearch esSearch=new EsSearch();
        esSearch.setId(fyPeople.getPeopleId());
        esSearch.setLanmu("资源-非遗传承人");
        esSearch.setLanmuId(2);
        esUnService.delete(esSearch);
        esSearch.setTitle(fyPeople.getPeopleName());
        esSearch.setContent(fyPeople.getPeopleBrief());
        esUnService.save(esSearch);
        if (com.ruoyi.common.utils.StringUtils.isNotEmpty(fyPeople.getProjectName())){

            FyProject projectList=  fyProjectService.selectFyProjectByProjectId(fyPeople.getProjectId());
            if (projectList!=null){
                fyPeople.setProjectType(projectList.getProjectType());
            }
        }
        return toAjax(fyPeopleService.updateFyPeople(fyPeople));
    }

    /**
     * 删除传承人信息
     */
//    @PreAuthorize("@ss.hasPermi('system:people:remove')")
    @Log(title = "传承人信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody DeleteIdVo deleteIdVo)
    {
        redisCache.deleteObject("home:count");
        return toAjax(fyPeopleService.deleteFyPeopleByPeopleIds(deleteIdVo.getPeopleIds()));
    }
    /**
     * 下载模版
     * @param response
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/template")
    @Log(title = "传承人", businessType = BusinessType.EXPORT)
    public void template(HttpServletResponse response) throws UnsupportedEncodingException {
        List<PeopleTemplateVo> list = new ArrayList<>();
        PeopleTemplateVo peopleTemplateVo=new PeopleTemplateVo();
        peopleTemplateVo.setPeopleName("张三");
        peopleTemplateVo.setPeopleBirth("2025.1.1");
        peopleTemplateVo.setPeopleSex("男");
        peopleTemplateVo.setPeopleMz("汉");
        peopleTemplateVo.setIsDl("否");
        peopleTemplateVo.setpName("项目名称1");
        peopleTemplateVo.setProjectName("申报项目名称");
        peopleTemplateVo.setPeopleLevel("国家级");
        peopleTemplateVo.setUnit("单位办事处");
        peopleTemplateVo.setPeopleBrief("这是传承人介绍");
               list.add(peopleTemplateVo);
        ExcelUtil<PeopleTemplateVo> util = new ExcelUtil<PeopleTemplateVo>(PeopleTemplateVo.class);
        String fileName = URLEncoder.encode("传承人上传模版" + ".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        util.exportExcel(response, list, "传承人上传模版");
    }

    //    @Log(title = "项目管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @Transactional
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<PeopleTemplateVo> util = new ExcelUtil<PeopleTemplateVo>(PeopleTemplateVo.class);
        List<PeopleTemplateVo> voList = util.importExcel(file.getInputStream());

        voList.stream().forEach(l->{
                FyPeople fyData=new FyPeople();
                BeanUtils.copyBeanProp(fyData,l);
            fyPeopleService.insertFyPeople(fyData);
            });

        return AjaxResult.success();
    }


    @GetMapping("/templatepeople")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    public void templatepeople(HttpServletResponse response) throws UnsupportedEncodingException {
        List<DataPeopleTemplateVo> list = new ArrayList<>();
        DataPeopleTemplateVo dataTemplateVo=new DataPeopleTemplateVo();
        dataTemplateVo.setDataName("资源名称");
        dataTemplateVo.setPeopleName("传承人名称（资源所属传承人）");
        dataTemplateVo.setPeopleCode("人工编码（对应图片音频文件名称，例：文件名称为：传统工艺.jpg，人工编码填写:传统工艺.jpg）");
        dataTemplateVo.setDataType("图片/影音/文件");
        dataTemplateVo.setDataFormat("jpg/mp3/mp4/PDF");
        dataTemplateVo.setJibie("浏览级");
        dataTemplateVo.setJigou("朝阳");
        dataTemplateVo.setZhuluPeople("张三");
        dataTemplateVo.setZhuluTime("2011年12月1日");
        list.add(dataTemplateVo);
        ExcelUtil<DataPeopleTemplateVo> util = new ExcelUtil<DataPeopleTemplateVo>(DataPeopleTemplateVo.class);
        String fileName = URLEncoder.encode("传承人资源上传模版" + ".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        util.exportExcel(response, list, "传承人资源上传模版");
    }
    @PostMapping("/importDatapeople")
    @Transactional
    public AjaxResult importDatapeople(MultipartFile excelfile,MultipartFile[] files) throws Exception
    {
        ExcelUtil<DataTemplateVo> util = new ExcelUtil<DataTemplateVo>(DataTemplateVo.class);
        List<DataTemplateVo> voList = util.importExcel(excelfile.getInputStream());
        for(DataTemplateVo l:voList){
            FyData fyData=new FyData();
            BeanUtils.copyBeanProp(fyData,l);
            fyData.setDataType(Long.valueOf(
                    l.getDataType().replaceAll("图片","1")
                            .replaceAll("影音","2").replaceAll("文件","3")));
            String type = l.getDataFormat();
            String endpoint = ruoYiConfig.getEndpoint().substring(ruoYiConfig.getEndpoint().lastIndexOf("/") + 1);
            String url = "https://" + ruoYiConfig.getBucketName() + "." + endpoint + "/" + type  + "/"+ DateUtils.YYYYMMDD() +"/" +  l.getPeopleCode() ;

            fyData.setDataUrl(url);
            FyPeople people=new FyPeople();
            people.setPeopleName(l.getProjectName());
            List<FyPeople> list = fyPeopleService.selectFyPeopleList(people);

            fyData.setPeopleId(list.get(0).getPeopleId());
            fyDataService.insertFyData(fyData);
        }
        for (MultipartFile file:files) {

            OSS ossClient = new OSSClientBuilder().build(ruoYiConfig.getEndpoint(), ruoYiConfig.getAccessKeyId(), ruoYiConfig.getAccessKeySecret());
            ObjectMetadata omd = new ObjectMetadata();
            String status = "";
            String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String imgName = file.getOriginalFilename();
            if (ossClient.doesBucketExist(ruoYiConfig.getBucketName())) {
                System.out.println("您已经创建Bucket：" + ruoYiConfig.getBucketName() + "。");
            } else {
                System.out.println("您的Bucket不存在，创建Bucket：" + ruoYiConfig.getBucketName() + "。");

                ossClient.createBucket(ruoYiConfig.getBucketName());
            }
            if (type == "mp4" || type.equals("mp4")) {
                omd.setContentType("video/mp4");
                status = "0";
            }
            if (type == "mp3" || type.equals("mp3")) {
                omd.setContentType("audio/mpeg");
                status = "0";
            }
            if (type == "pdf" || type.equals("pdf") || type.equals("PDF") || type == "PDF") {
                omd.setContentType("application/pdf");
                status = "0";
            }
            if (type == "jpg" || type.equals("jpg")) {
                omd.setContentType("image/jpg");
                status = "0";
            }
            if (type == "png" || type.equals("png")) {
                omd.setContentType("image/jpg");
                status = "0";
            }
            if (StringUtils.isEmpty(status)) {
                return AjaxResult.error("请输入上传正确格式的文件--> .jpg/.png/mp4/mp3/.pdf");
            }
            String endpoint = ruoYiConfig.getEndpoint().substring(ruoYiConfig.getEndpoint().lastIndexOf("/") + 1);
            ossClient.putObject(ruoYiConfig.getBucketName(), type + "/"+ DateUtils.YYYYMMDD() +"/" + imgName, file.getInputStream(), omd);
            String url = "https://" + ruoYiConfig.getBucketName() + "." + endpoint + "/" + type  + "/"+ DateUtils.YYYYMMDD() +"/" +  imgName + ruoYiConfig.getOssshuiyin();
            ossClient.setObjectAcl(ruoYiConfig.getBucketName(), type  + "/"+ DateUtils.YYYYMMDD() +"/" + imgName, CannedAccessControlList.PublicRead);
            ossClient.shutdown();
            ossClient.shutdown();
        }

        return AjaxResult.success();
    }

}
